package com.css.security.core.authorization;

import com.css.common.security.constant.SecurityConstants;
import com.css.common.security.properties.SecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;

/**
 * CssAuthorizeConfigProvider
 * 核心模块的授权配置提供器，安全模块涉及的url的授权配置在这里。
 * - @Order值越小拥有越高的优先级
 *
 * @author hanyx
 * @date 2019/04/18
 */
@Component
@Order(Integer.MIN_VALUE)
public class CssAuthorizeConfigProvider implements AuthorizeConfigProvider {

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * .authorizeRequests() 的返回对象
     *
     * @param config
     */
    @Override
    public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {

        // 授权配置 - 不需要登录可以访问
        config.antMatchers("/",
                SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE,
                SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_OPENID,
                SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/image",
                SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/sms",
                securityProperties.getBrowser().getSignInPage(),
                securityProperties.getBrowser().getSignUpUrl(),
                securityProperties.getBrowser().getSession().getSessionInvalidUrl()
        ).permitAll();

        // 判断swagger开关
        if (securityProperties.getBrowser().isSwaggerEnabled()) {
            config.antMatchers("/swagger-ui.html",
                    "/swagger-resources/**",
                    "/images/**",
                    "/webjars/**",
                    "/v2/api-docs",
                    "/configuration/ui",
                    "/configuration/security"
            ).authenticated();
        }

        // 判断你是否添加退出路径
        if (StringUtils.isNotBlank(securityProperties.getBrowser().getSignOutUrl())) {
            config.antMatchers(securityProperties.getBrowser().getSignOutUrl()).permitAll();
        }
        return false;
    }
}
